<template>
  <el-form :model="form" ref="ruleFormRef" :label-position="labelPosition" label-width="100px" :inline="true"
    :rules="rules" status-icon class="demo-form-inline">
    <el-form-item style="width: 61%" label="平台名称" prop="name">
      <el-input v-model="form.name" maxlength="50" show-word-limit clearable />
    </el-form-item>

    <el-form-item label="平台简称" >
      <el-input v-model="form.abbreviation" maxlength="19" show-word-limit clearable  />
    </el-form-item>
    <el-form-item label="负责人" prop="headName">
      <!-- <SelectOption :selectValue="form.headBy" :options="data.userAllList" @change-value="changeValue"> </SelectOption> -->
      <user-list-modal
          v-model="form.headName"
          @update:modelValue="handleProjectLeader"
          :default-users="[]"
          :multiple="false"
          :devType="'platform'" clearable
      />
    </el-form-item>
    <el-form-item label="联系电话" prop="phone" >
      <el-input v-model="form.phone" maxlength="15" clearable />
    </el-form-item>

    <el-form-item label="研究领域" prop="reFieldName">
      <SelectOption :selectValue="form.reFieldName" :options="data.researchSelect" @change-value="changeValue1" clearable >
      </SelectOption>
    </el-form-item>

    <el-form-item label="承建单位"  prop="conUnit">
      <!-- <SelectOption :selectValue="form.conUnit" :options="data.orgAllList" @change-value="changeValue2"> </SelectOption> -->
      <popup-tree-input
        :data="data.orgAllList"
        :props="data.popupTreeProps"
        :prop="
        deptForm.parentName == null
        ? $t('message.org.top_menu')
        : form.conUnitName
        "
        :node-key="'' + deptForm.parentId"
        :current-change-handle="changeValue2" clearable
      />
    </el-form-item>

    <el-form-item label="平台级别" prop="levelName">
      <SelectOption :selectValue="form.levelName" :options="data.levelOptions" @change-value="changeValue3" clearable >
      </SelectOption>
    </el-form-item>

    <el-form-item label="专业类别" prop="typeName">
      <SelectOption :selectValue="form.typeName" :options="data.typeOptions" @change-value="changeValue4" clearable > </SelectOption>
    </el-form-item>

    <el-form-item label="认定机构" prop="rdDept">
      <!-- <SelectOption :options="options" @change-value="changeValue5"> </SelectOption> -->
      <el-input v-model="form.rdDept" maxlength="50"  show-word-limit clearable   />
    </el-form-item>

    <el-form-item label="认定日期" prop="rdDate">
      <el-date-picker v-model="form.rdDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        @change="handleChangeDate" />
    </el-form-item>

    <el-form-item label="评估周期（单位/年）" label-width="160px" prop="evCycle">
      <el-input oninput="value=value.replace(/^0|[^0-9]/g,'')" type="number" v-model="form.evCycle" maxlength="3" clearable  />
    </el-form-item>

    <el-form-item label="建设方式" prop="wayName">
      <SelectOption :selectValue="form.wayName" :options="data.constructSelect" @change-value="changeValue6" clearable >
      </SelectOption>
    </el-form-item>

    <el-form-item label="平台状态" prop="plaStatusName">
      <SelectOption :selectValue="form.plaStatusName" :options="data.stateSelect" @change-value="changeValue7" clearable >
      </SelectOption>
    </el-form-item>

    <el-form-item label="依托单位" prop="plaUnit">
      <!-- <SelectOption :selectValue="form.plaUnit" :options="data.orgAllList" @change-value="changeValue8"> </SelectOption> -->
      <popup-tree-input
        :data="data.orgAllList"
        :props="data.popupTreeProps"
        :prop="
        deptForm.parentName == null
        ? $t('message.org.top_menu')
        : form.plaUnitName
        "
        :node-key="'' + deptForm.parentId"
        :current-change-handle="changeValue8"
        />
    </el-form-item>

    <el-form-item label="在职人数">
      <el-input  v-model="form.jobNums" oninput="value=value.replace(/[^0-9]/g,'')" min="0"  maxlength="5" clearable  />
    </el-form-item>

    <el-form-item label="传真">
      <el-input  v-model="form.faxes" oninput="value=value.replace(/[^0-9]/g,'')"  :min="0" type="number" maxlength="20"  show-word-limit clearable   />
    </el-form-item>

    <el-form-item label="网址"  prop="wbUrl">
      <el-input v-model="form.wbUrl" maxlength="300"  show-word-limit clearable   />
    </el-form-item>

    <el-form-item label="学历博士以上人数" label-width="110px" style="width: 35%">
      <el-input   v-model="form.drNums" oninput="value=value.replace(/[^0-9]/g,'')" :min="0" maxlength="5"/>
    </el-form-item>

    <el-form-item label="职称中级以上人数" label-width="110px" style="width: 35%">
      <el-input   v-model="form.inteNums" oninput="value=value.replace(/[^0-9]/g,'')" :min="0" maxlength="5"/>
    </el-form-item>

    <el-form-item label="共建单位" style="width: 100%" prop="cjUnitName" >
      <div class="selectLabel">
        <el-tag v-for="tag in callUnit" :key="tag.id" class="mx-1" closable @close="handleCloseUnit(tag)">
          {{ tag.value }}
        </el-tag>
      </div>
      <span class="addLabel" @click="addUnitBox">添加单位</span>
    </el-form-item>

    <el-form-item style="width: 100%" label="平台简介" prop="deptIntroduction">
      <el-input v-model="form.deptIntroduction" :autosize="{ minRows: 2 }" maxlength="1000"    show-word-limit clearable    type="textarea"
        placeholder="请输入" />
    </el-form-item>

    <el-form-item label="研究方向" style="width: 100%" prop="reDirection">
      <el-input v-model="form.reDirection" :autosize="{ minRows: 2 }" maxlength="1000"    show-word-limit clearable   type="textarea"
        placeholder="请输入" />
    </el-form-item>

    <el-form-item label="承担并完成的国家科技计划项目基本情况" class="labelHeight" style="width: 100%">
      <el-input v-model="form.sitPlan" :autosize="{ minRows: 3 }" maxlength="1000"    show-word-limit clearable   type="textarea" placeholder="请输入" />
    </el-form-item>

    <el-form-item label="主持和参与制定的国际、国家、行业标准情况" class="labelHeight" style="width: 100%">
      <el-input v-model="form.sitStandard" :autosize="{ minRows: 3 }" maxlength="1000"   show-word-limit clearable    type="textarea"
        placeholder="请输入" />
    </el-form-item>

    <el-form-item label="获国家自然科学、技术发明、科技进步奖项目情况" class="labelHeight" style="width: 100%">
      <el-input v-model="form.sitAwards" :autosize="{ minRows: 3 }" maxlength="1000"   show-word-limit clearable    type="textarea" placeholder="请输入" />
    </el-form-item>
  </el-form>

  <!-- <el-button type="primary" @click="submitForm()">保存</el-button> -->

  <el-dialog v-model="data.addUnit" append-to-body width="50%" top="10vh" :show-close="false"
    :close-on-click-modal="false">
    <template #title>
      <el-tabs v-model="data.activeName" class="demo-tabs">
        <el-tab-pane label="选择单位" name="first">
          <div>
            <el-row>
              <el-col :span="24">
                <p>内部单位：</p>
                <el-cascader-panel :options="selOp" v-model="innerValue"
                  :props="{ emitPath: false, value: 'id', label: 'name',checkStrictly: true }" :show-all-levels="false"
                  @change="innerValueChange" />
              </el-col>
              <el-col :span="24" style="margin-top: 15px;">
                <span>外部单位：</span>
                <el-input v-model="data.outsideValue" style="width: 200px;margin-right: 15px;" />
                <el-button type="primary" @click="addOutside()">添加</el-button>
              </el-col>
            </el-row>
            <div class="unitBox">
              <div class="title">已选单位</div>
              <div class="tagBox">
                <el-tag v-for="tag in unit" :key="tag" class="mx-1" closable @close="handleClose(tag)">
                  {{ tag.value }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.addUnit = false">关闭</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import UserListModal from '@/views/project/components/UserListModal/index.vue';
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue';
import SelectOption from '@/views/science/components/selectOption/index.vue';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useStore } from 'vuex';

export default {
  components: {
    SelectOption,PopupTreeInput,UserListModal
  },
  emits: {
    valueFlag: null,
  },
  setup(props, { emit }) {
    const store = useStore()
    const labelPosition = ref('right')

    const data = reactive({
      activeName: ref('first'),
      popupTreeProps: {
        label: 'name',
        children: 'children',
      },
      addUnit: false,
      innerValue: '',
      outsideValue: '',
      researchSelect: computed(() => store.state.technologyStrength.researchSelect),
      levelOptions: computed(() => store.state.technologyStrength.gdlevelSelect),
      typeOptions: [],
      constructSelect: computed(() => store.state.technologyStrength.gdconstructSelect),
      stateSelect: computed(() => store.state.technologyStrength.stateSelect),
      userAllList: computed(() => store.state.technologyStrength.userAllList),
      // orgAllList: computed(() => store.state.technologyStrength.orgAllList),
      orgAllList:[],
      // cjUnit: computed(() => store.state.technologyStrength.form.cjUnit),
      // cjUnitName: computed(() => store.state.technologyStrength.form.cjUnitName),
      // cjUnit2: computed(() => store.state.technologyStrength.form.cjUnit2),
      // // cjUnit: "",
      // cjUnit2: ""
    })
    const deptForm = {
      parentId: 0,
      parentName: '',
    }
    const form = reactive(store.state.technologyStrength.form)
    if (form.level) {
      data.levelOptions.map((item) => {
        if (item.itemValue == form.level) {
          data.typeOptions = item.children
        }
      })
    }
    watch(form, (newValue, oldValue) => {
      store.commit('technologyStrength/getForm', { ...form })
    });
    const changeValue1 = (item) => {
      form.reField = item.itemValue
      form.reFieldName = item.itemText
    }
    const changeValue2 = (item) => {
      // if (item) {
      //   form.conUnit = item.id
      //   form.conUnitName = item.name
      // }else{
      //   form.conUnit = ''
      //   form.conUnitName = ''
      // }
      form.conUnit = item.id
      form.conUnitName = item.name
    }
    const changeValue3 = (item) => {
      form.level = item.itemValue
      form.levelName = item.itemText
      data.typeOptions = item.children
      form.type = ''
      form.typeName = ''
    }
    const changeValue4 = (item) => {
      form.type = item.itemValue
      form.typeName = item.itemText
    }
    const changeValue5 = (item) => {
      form.rdDept = item.id
      form.rdDeptName = item.name
    }
    const changeValue6 = (item) => {
      console.log(item)
      form.way = item.itemValue
      form.wayName = item.itemText
    }
    const changeValue7 = (item) => {
      form.plaStatus = item.itemValue
      form.plaStatusName = item.itemText
    }
    const changeValue8 = (item) => {
      form.plaUnit = item.id
      form.plaUnitName = item.name
    }

    const rules = reactive({
      name: [
        { required: true, message: '请输入平台名称', trigger: 'blur' },
      ],
      headName: [
        { required: true, message: '请选择负责人', trigger: 'change', },
      ],
      phone: [
        { required: false, message: '请输入电话号码', trigger: 'change', },
        { pattern: /^1[3456789]\d{9}$/, message: '电话号码格式不正确', trigger: 'blur' },
      ],
      reFieldName: [
        { required: true, message: '请选择研究领域', trigger: 'change', },
      ],
      conUnit: [
        { required: true, message: '请选择承建单位', trigger: 'change', },
      ],
      levelName: [
        { required: true, message: '请选择平台级别', trigger: 'change', },
      ],
      typeName: [
        { required: true, message: '请选择专业类别', trigger: 'change', },
      ],
      rdDept: [
        { required: true, message: '请输入认定机构', trigger: 'blur', },
      ],
      rdDate: [
        { required: true, message: '请输入认定日期', trigger: 'blur', },
      ],
      evCycle: [
        { required: true, message: '请输入评估周期', trigger: 'blur', },
      ],
      wayName: [
        { required: true, message: '请选择建设方式', trigger: 'change' },
      ],
      plaStatusName: [
        { required: true, message: '请选择平台状态', trigger: 'change' },
      ],
      plaUnit: [
        { required: true, message: '请选择依托单位', trigger: 'change' },
      ],
      cjUnitName: [
        { required: true, message: '请选择共建单位', trigger: 'change' },
      ],
      deptIntroduction: [
        { required: true, message: '请输入简介', trigger: 'blur' },
      ],
      reDirection: [
        { required: true, message: '请输入研究方向', trigger: 'blur' },
      ],
      wbUrl: [
        {required: false, message: '请输入网址', trigger: 'change', },
        { pattern: /^((https|http|ftp|rtsp|mms){0,1}(:\/\/){0,1})www\.(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/i, message: '网址格式不正确', trigger: 'blur' },
      ],
    })

    const ruleFormRef = ref()
    const submitForm = async () => {
      await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          emit('valueFlag', true)
          console.log('submit!')
        } else {
          emit('valueFlag', false)
        }
      })
    }

    const callUnit: any = ref([])
    let unit: any = ref([])


    watch(() => form.cjUnit, () => {
      console.log(form,form.cjUnit,form.cjUnitName)
      let str = form.cjUnitName +","+ form.cjUnit2
      let arr1: string[] = str ? str.split(",") : [];
      let arr2: string[] = form.cjUnit ? form.cjUnit.split(",") : [];
      console.log(arr1)
      callUnit.value = arr1.map((id: string, index: number) => ({
        value: arr1[index],
        id:arr2[index],
      }))
    })


    const save = () => {
      callUnit.value = unit.value
      data.addUnit = false
    }

    const findItemNested = (arr, itemId, nestingKey) => (
      arr.reduce((a, item) => {
        if (a) return a;
        if (item.id === itemId) return item;
        if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
      }, null)
    );

    const selOp = computed(() => {
      // const obj = store.state.technologyStrength.orgAllList
      const obj = data.orgAllList
      let arr = [] as any
      for (let key in obj) {
        arr.push(obj[key])
      }
      return arr
    })

    const addUnitBox = () => {
      unit.value = callUnit.value.map((item) => {
        return item
      })
      data.addUnit = true
    }

    const handleUnitString = (data, item) => {
      if (data) {
        let arr = data.split(',')
        var index = arr.indexOf(item);
        if (!(index > -1)) { // 代表不存在，
          arr.push(item);
        } else {
          arr.splice(index, 1)
        }
        return arr.join(',')
      } else {
        let arr: any = []
        arr.push(item)
        return arr.join(',')
      }
    }

    const innerValue = ref()

    const innerValueChange = (value) => {
      const item = findItemNested(selOp.value, value, 'children')
      unit.value.push({
        id: item.id,
        value: item.name
      })
      form.cjUnitName = handleUnitString(form.cjUnitName, item.name)
      form.cjUnit = handleUnitString(form.cjUnit, item.id)
    }

    const addOutside = () => {
      if (data.outsideValue) {
        unit.value.push({
          id: '',
          value: data.outsideValue
        })

        form.cjUnit2 = handleUnitString(form.cjUnit2, data.outsideValue)
      }

      data.outsideValue = ''
    }

    const handleCloseUnit = (tag) => {
      callUnit.value.splice(callUnit.value.indexOf(tag), 1)

      if (tag.id) {
        form.cjUnitName = handleUnitString(form.cjUnitName, tag.value)
        form.cjUnit = handleUnitString(form.cjUnit, tag.id)
      } else {
        form.cjUnit2 = handleUnitString(form.cjUnit2, tag.value)
      }
    }

    const handleClose = (tag) => {
      unit.value.splice(unit.value.indexOf(tag), 1)
      if (tag.id) {
        form.cjUnitName = handleUnitString(form.cjUnitName, tag.value)
        form.cjUnit = handleUnitString(form.cjUnit, tag.id)
      } else {
        form.cjUnit2 = handleUnitString(form.cjUnit2, tag.value)
      }
    }

    const handleChangeDate = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.rdDate = formattedDate
      store.commit('technologyStrength/getForm', { ...form })
    }
    const getOrgList = () =>{
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res =>{
        console.log('getOrgList',res);
        data.orgAllList = res.data.data
      })
    }
    //选择人员的回调
    const handleProjectLeader = (user) => {

      if(user.userId){

        form.headBy = user.userId
        form.headName = user.cname
        form.phone = user.phone
      }
    }

    onMounted(() =>{
      getOrgList()
    })
    return {
      labelPosition,
      data,
      form,
      selOp,
      unit,
      callUnit,
      innerValue,
      rules,
      submitForm,
      ruleFormRef,

      handleChangeDate,

      changeValue1,
      changeValue2,
      changeValue3,
      changeValue4,
      changeValue5,
      changeValue6,
      changeValue7,
      changeValue8,

      addUnitBox,
      addOutside,
      handleClose,
      handleCloseUnit,
      innerValueChange,
      save,
      getOrgList,
      deptForm,
      handleProjectLeader,
    }
  },
}
</script>
<style lang="scss" scoped>
.demo-form-inline .el-form-item {
  width: 30%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
  margin-top: 6px;
  vertical-align: top;
}

.unitBox {
  width: 100%;
  margin: 30px 0;

  .title {
    padding: 15px 0;
    border-bottom: 1px solid #ccc;
  }

  .tagBox {
    line-height: 40px;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px 15px;
  }
}

.el-tag {
  margin-right: 10px;
}
</style>
